package com.ynny.chapter09.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/files")
public class DownloadController {


    @GetMapping("/download")
    public ResponseEntity downloadFile(@RequestParam(name = "fileName")
                                           String fileName){

        //构建文件路径 使用传入的文件名称
        //保存一个文件出来

        File file = new File("D:/upload/" + fileName);

        if (!file.exists()){
            return ResponseEntity.notFound().build();
        }

        Resource resource = new FileSystemResource(file);

        //响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + resource.getFilename());

        //返回对象
        return  ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)  // 设置内容类型
                .body(resource);  // 设置响应体为文件资源



    }

}
